﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Util;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PrenatalCheckup
{
    /// <summary>
    /// 删除种母妊检
    /// </summary>
    public class DeletedPrenatalCheckupHandler : IRequestHandler<DeletedPrenatalCheckupCommand, Result>
    {
        /// <summary>
        /// 种母妊检ID
        /// </summary>
        private readonly IBaseRepository<PrenatalCheckups> _prenatalCheckupsRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DeletedPrenatalCheckupHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="prenatalCheckupsRepository"></param>
        /// <param name="logger"></param>
        public DeletedPrenatalCheckupHandler(IBaseRepository<PrenatalCheckups> prenatalCheckupsRepository,
                                             ILogger<DeletedPrenatalCheckupHandler> logger)
        {
            _prenatalCheckupsRepository = prenatalCheckupsRepository;
            _logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeletedPrenatalCheckupCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                //根据前台传入的ID查询种母妊检表有没有该数据
                var query = await (await _prenatalCheckupsRepository.GetAll()).Where(x => request.PrenatalCheckupId.Contains(x.PrenatalCheckupId)).ToListAsync();
                //如果有值 循环修改删除字段 改成已删除 1-未删除 2-已删除
                if (query.Count != 0)
                {
                    //遍历修改
                    query.ForEach(d =>
                    {
                        d.IsPrenatalCheckUp = 2;
                    });
                    //修改
                    var res = _prenatalCheckupsRepository.UpdRange(query);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "删除成功";
                    }
                }
                else
                {
                    result.Msg = "未获取到值,请重新选择";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "删除种母妊检" + ex.Message;
                _logger.LogError("删除种母妊检异常" + ex.Message);
            }
            return result;
        }
    }
}
